<template>
  <div class='comicInfo' :style="{backgroundColor:`#${comicInfo.background_color}`}">
    <!-- 封面 -->
    <div class="cover">
      <div class="bgBox">
        <img class='bgImg' :src='loadImg' :style="{background:`url(${comicInfo.cover_list[0]}) center center / cover no-repeat`}">
      </div>
      <!-- 标题内容 -->
      <div class="comicTitle flex">
        <div class="info">
          <h2>{{comicInfo.comic_name}}</h2>
          <div class="other">
            <p>人气：{{formatRenQi(comicInfo.total_heat)}}</p>
            <div class="type flex">
              <span class='typename'>类型：</span>
              <div class="flex typeList">
                <div class='typeItem' v-for="t in comicInfo.comic_type" :key="t.id">
                  {{ t }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="desc">
      <h5 class='box-title'>详情</h5>
      <div class="info">
        {{comicInfo.comic_desc}}
      </div>
    </div>
    <div class="sort">
      <h5 class="box-title">排名</h5>
      <div class="flex sort-detail">
        <span>本周人气：{{formatRenQi(comicInfo.week_heat)}}</span>
        <span>排名：{{comicInfo.week_heat_rank}}</span>
        <span>状态：{{comicInfo.rise_week_rank}}</span>
      </div>
    </div>
    <div class="catalog">
      <div class="flex catalogMenu">
        <div class='flex' style="align-items: center">
          <h5 class="box-title">目录</h5>
          <i @click='onSort(1)' class="fa fa-caret-up" style='margin-right:10px' :class='{"active":sort==1}'></i>
          <i @click='onSort(0)' class="fa fa-caret-down" :class='{"active":sort==0}'></i>
        </div>
        <div class="catalogNav">
          <!-- fadeOutUp -->
          <span @click='showNav = !showNav'>选集</span>
          <div class="navbox animated" :class="[showNav?'fadeInDown':'fadeOutUp']">
            <div class="navlist flex">
              <div @click='goNav(index)' class=navItem v-for="item,index in catalognav" :key="item.id">
                {{ item }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="catalog_status">
        {{comicInfo.comic_status==1?'连载中':'完结'}}
        {{comicInfo.last_chapter_name}}
      </div>
      <div class="catalogList">
        <div v-for="item in catalogList" class='flex flex-column catalogItem' :key="item.id">
          <p @click='goRead(item.chapter_name)' :class="{active:curcatalogTitle==item.chapter_name&&isCache}"><span
              class='catalogDate'>
              {{formatDate(item.create_date)}}
            </span>
            <span :data-itemId='item.cataId'>{{item.chapter_name}}</span>
          </p>
        </div>
      </div>
    </div>
    <div class="recommend">
      <h5 class="box-title">相关推荐</h5>
      <div class="flex recommend-detail flex-wrap">
        <figure @click='toCmicInfo(item.comic_id)' v-for="item in recommends" class='item' :key="item.id">
          <img class='img' v-lazy="`https://image.mhxk.com/mh/${item.cartoon_id}_2_1.jpg-noresize.webp`" alt="">
          <figcaption class='text-warp'>{{item.cartoon_name}}</figcaption>
        </figure>
      </div>
    </div>
    <!-- 看了又看 -->
    <div class="recommend">
      <h5 class="box-title">看了又看</h5>
      <div class="flex recommend-detail flex-wrap">
        <figure @click='toCmicInfo(item.comic_id)' v-for="item in seeAgains" class='item' :key="item.id">
          <img class='img' v-lazy="`https://image.mhxk.com/mh/${item.cartoon_id}_2_1.jpg-noresize.webp`" alt="">
          <figcaption class='text-warp'>{{item.cartoon_name}}</figcaption>
        </figure>
      </div>
    </div>
    <!-- 猜你喜欢 -->
    <div class="recommend">
      <h5 class="box-title">猜你喜欢</h5>
      <div class="flex recommend-detail flex-wrap">
        <figure @click='toCmicInfo(item.comic_id)' v-for="item in gussLikes" class='item' :key="item.id">
          <img class='img' v-lazy="`https://image.mhxk.com/mh/${item.cartoon_id}_2_1.jpg-noresize.webp`" alt="">
          <figcaption class='text-warp'>{{item.cartoon_name}}</figcaption>
        </figure>
      </div>
    </div>
    <!-- 评论区 -->
    <div class="comment">
      <h5 class="box-title">热门评论</h5>
      <div class="flex box" v-for="item in commentTops" :key="item.id">
        <div v-if="item.user" class="headimg">
          <mu-avatar>
            <img onerror='this.src="/public/images/error.png"' :src="showHeadImg(item.user.Uid)">
          </mu-avatar>
        </div>
        <div class="panel flex flex-column">
          <div v-if="item.user" class="name">{{item.user.Uname}}</div>
          <div class="content" v-html="formatemoji(item.content)"></div>
          <small><time>{{formatCommDate(item.createtime)}}</time></small>
        </div>
        <!-- <mu-divider></mu-divider> -->
      </div>
      <div v-if="commentTops.length==0" class="noinfo">
        <span>暂时还没有评论哦~</span>
      </div>
      <div class="finish" v-if="commentEnd">
        <span>没有更多啦。</span>
      </div>
      <div v-if="commentTops.length>0" @click='loadmoreComment' class="loadmore flex">
        <span>加载更多</span>
      </div>
    </div>
    <div class="fab" :style="{opacity:showtopBtn?.7:0}">
      <mu-button @click='totop' fab small color="#ffb48e">
        <i class="fa fa-arrow-up"></i>
      </mu-button>
    </div>
    <!-- <mu-list textline="three-line">
      <mu-sub-header>热门评论</mu-sub-header>
      <mu-list-item avatar :ripple="false" button>
        <mu-list-item-action>
          <mu-avatar>
    </mu-avatar>
    </mu-list-item-action>
    <mu-list-item-content>
      <mu-list-item-title>{{item.user.Uname}}</mu-list-item-title>
      <mu-list-item-sub-title>
        {{item.content}}
      </mu-list-item-sub-title>
    </mu-list-item-content>
    </mu-list-item>
    <mu-divider></mu-divider>
    </mu-list> -->
    <div @click='goRead' class="readbtn flex">
      <div v-if="curcatalogTitle">
        {{curcatalogTitle}}
      </div>
      <div>
        {{isCache?'继续阅读':'开始阅读'}}
      </div>
    </div>
  </div>
</template>
<style>
  @import './comicInfo';

</style>
<script>
  import date from './../commponent/utils/date';
  import tool from './../util/tool';
  export default {
    data() {
      return {
        comInfoLg: null,
        curcatalogTitle: '',
        sort: 0,
        comicId: 106382,
        gussLikes: [],
        seeAgains: [],
        recommends: [],
        loadImg: './../../../public/images/space.gif',
        comicInfo: {
          background_color: '',
          comic_author: '',
          comic_desc: '',
          comic_media: '',
          comic_name: '',
          comic_status: '',
          comic_type: [],
          cover_list: [],
          copyright_type_cn: '',
          last_chapter_id: '',
          last_chapter_name: '',
          shoucang: '',
          total_heat: '',
          week_heat: '',
          week_heat_rank: '',
          rise_week_rank: ''
        },
        catalogList: [],
        catalognav: [],
        showNav: false,
        commentTops: [],
        curpageComment: 1,
        showtopBtn: false,
        isCache: false,
        commentEnd: false
      };
    },
    methods: {
      toCmicInfo(comicId) {
        if (!comicId) return false;
        this.comicId = comicId;
        this.$router.push({
          path: '/main/comicInfo',
          query: {
            comicId: comicId
          }
        });
        this.init();
      },
      isNum(num) {
        return isNaN(num) ? false : true;
      },

      goRead(title) {
        if (typeof title !== 'string') {
          title = this.curcatalogTitle;
        }
        this.comInfoLg.setItem('comicId', this.comicId);
        this.$router.push(`/main/read?title=${title}&comicId=${this.comicId}&comicName=${this.comicInfo.comic_name}`);
        // this.$router.push('/read?title=' + this.curcatalogTitle || title + '&cache=1');
      },
      // 导航目录
      goNav(index) {
        let curIndex = index * 20 + 1;
        let currentDomTop = document.querySelector('span[data-itemid="' + curIndex + '"]').getBoundingClientRect().top -
          10;
        // let topDomH = document.querySelector('.top').clientHeight;
        let targetDom = document.querySelector('.comicInfo');
        let curTop = targetDom.scrollTop;
        let totalTop = curTop + currentDomTop;
        let timer = setInterval(() => {
          if (curTop >= totalTop) {
            targetDom.scrollTop = totalTop;
            clearInterval(timer);
            return false;
          }
          targetDom.scrollTop = curTop;
          curTop += totalTop / 6;
        }, 100);
        this.showNav = false;
      },
      totop() {
        document.querySelector('.comicInfo').scrollTop = 0;
      },
      showHeadImg(num) {
        let str = num + '';
        while (str.length < 9) {
          str = '0' + str;
        }
        str = str.replace(/(?=(\B)(\d{3})+$)/g, ',').split(',').join('/');
        return `https://image.mhxk.com/file/kanmanhua_images/head/${str}.jpg-noresize.webp`;

      },
      formatCommDate(time) {
        return date(time, 'YYYY年MM月DD日');
      },
      // 格式化目录
      formatCatalog(num) {
        let length = Math.ceil(num / 20);
        let arr = [];
        for (let i = 0; i < length; i++) {
          if ((i + 1) * 20 < num) {
            arr.push(i * 20 + 1 + `-${(i+1)*20}`);
          } else {
            arr.push(i *
              20 + 1 == num ? num : i * 20 + 1 + `-${num}`);
          }
        }
        return arr;
      },
      formatDate(time) {
        return date(time * 1000, 'YYYY-MM-DD');
      },
      formatRenQi(num) {
        num = (num || 0).toString();
        let result = [];
        let wit = ["亿", "万"];
        let res = "";
        while (num.length > 3) {
          result.push(num.slice(-4));
          num = num.slice(0, num.length - 4);
        }
        if (num) {
          result.push(num);
        }
        if (result.length == 1) {} else if (result.length == 2) {
          res = result[1] + wit[1];
        } else if (result.length == 3) {
          res = result[2] + "." + result[1].slice(0, 2) + wit[0];
        }
        return res;
      },
      onSort(num) {
        if (num == 1 && this.sort == 0) {
          this.catalogList.reverse();
          this.sort = 1;
        } else if (num == 0 && this.sort == 1) {
          this.catalogList.reverse();
          this.sort = 0;
        }
        // this.comInfoLg.setItem('list', this.catalogList);
      },
      loadmoreComment() {
        this.curpageComment++;
        this.getComment();
      },
      formatemoji(str) {
        return str.replace(/\{emoji:馒头仔\/\d+}/g, item => {
          let num = item.replace(/\D/g, "");
          return `<img height='32' alt='馒头仔${num}' src='https://image.zymk.cn/file/emot/%E9%A6%92%E5%A4%B4%E4%BB%94/${num}.gif'>`;
        });
      },
      getComment() {
        this.$http.get('http://y.yuduo.top/index/Manhua/getComment', {
          params: {
            comicId: this.comicId,
            page: this.curpageComment
          }
        }).then(res => {
          let result = null;

          if (res.status == 200 && res.data) {
            // result = JSON.parse(res.data).data;
            result = res.data.data;
          }
          let userids = ''
          if (result.length == 0) {
            this.commentEnd = true;
            return;
          }
          result.map(item => {
            userids += ',' + item.useridentifier;
          })
          userids = userids.slice(1);
          this.$http.get('http://y.yuduo.top/index/manhua/getuserinfo?userids=' + userids).then(res => {
            if (res.status == 200 && res.data) {
              let users = res.data.data;
              if (!users) return;
              result.map((item, index) => {
                users.map((user, userindex) => {
                  if (user.Uid == item.useridentifier) {
                    item['user'] = user;
                  }
                })
                this.commentTops.push(item);
              })
            }
          })
        });
      },
      getCommentTop() {
        this.$http.get('http://y.yuduo.top/index/Manhua/getCommentTop', {
          params: {
            comicId: this.comicId
          }
        }).then(res => {
          let result = null;
          if (res.status == 200 && res.data) {
            result = JSON.parse(res.data).data;
          }
          if (result.length == 0) return;
          let userids = ''
          result.map(item => {
            userids += ',' + item.useridentifier;
          })
          userids = userids.slice(1);
          this.$http.get('http://y.yuduo.top/index/manhua/getuserinfo?userids=' + userids).then(res => {
            if (res.status == 200 && res.data) {
              let users = res.data.data;
              users.map((user, userindex) => {
                result.map((item, index) => {
                  if (user.Uid == item.useridentifier) {
                    result[index]['user'] = user;
                  }
                })
              })
            }
            this.commentTops = result;
            this.getComment();
          })
        })
      },
      init() {
        this.$progress.start();
        // 加载漫画信息
        this.$http.get('http://y.yuduo.top/index/manhua/getMhInfo', {
          params: {
            comicId: this.comicId
          }
        }).then(res => {
          if (this.comInfoLg) {
            this.comInfoLg.removeItem('list');
          }
          // console.log(res);
          let data = res.data;
          if (typeof data == 'string') {
            data = JSON.parse(data).data;
          };

          let tempRes = data; // res.data.data;
          // 给定值赋值与对象上
          for (const obj in this.comicInfo) {
            if (this.comicInfo.hasOwnProperty(obj)) {
              this.comicInfo[obj] = tempRes[obj];
            }
          }
          this.comInfoLg.setItem('lastCmicInfo', this.comicInfo);
          // 存储当前漫画信息到缓存
          this.comInfoLg.setItem('list', tempRes['comic_chapter'].reverse());
          tempRes['comic_chapter'].map((item, index) => {
            if (index % 20 == 1) {
              tempRes['comic_chapter'][index]['cataId'] = index;
            }
          })
          this.catalogList = tempRes['comic_chapter'];
          this.catalognav = this.formatCatalog(this.catalogList.length);
          this.comInfoLg.getItem('comicId').then((val) => {
            if (!val || this.comicId != val) return;
            this.comInfoLg.getItem('history').then(hisList => {
              hisList.forEach(item => {
                if (val === item.comicId) {
                  this.isCache = true;
                  this.curcatalogTitle = item.title;
                }
              })
            })
          })
          this.curcatalogTitle = !this.curcatalogTitle ? (this.catalogList[0] ? this.catalogList[0].chapter_name :
            '') : this.curcatalogTitle;
          // 加载相关漫画
          this.$http.get('http://y.yuduo.top/index/manhua/getOthermh', {
            params: {
              comType: 1,
              comicId: this.comicId
            }
          }).then(res => {
            let result = res.data.data;
            this.recommends = tool.shuffle(result.comic_info).slice(0, 6);
          })
          // 加载看了又看
          this.$http.get('http://y.yuduo.top/index/manhua/getOthermh', {
            params: {
              comType: 2,
              comicId: this.comicId
            }
          }).then(res => {
            let result = res.data.data;
            this.seeAgains = tool.shuffle(result.comic_info).slice(0, 6);
          })
          // 加载猜你喜欢
          this.$http.get('http://y.yuduo.top/index/manhua/getOthermh', {
            params: {
              comType: 3,
              comicId: this.comicId
            }
          }).then(res => {
            let result = res.data.data;
            this.gussLikes = tool.shuffle(result.comic_info).slice(0, 6);
          })
          document.querySelector('.comicInfo').scrollTop = 0;
          this.$progress.done();
          // 获取评论
          this.getCommentTop();
        });
      },
      scrollfun() {
        if (document.querySelector('.comicInfo').scrollTop > 400) {
          this.showtopBtn = true;
        } else {
          this.showtopBtn = false;
        }
      }
    },
    mounted() {
      this.comicId = this.$route.query.comicId;
      if (!this.comicId) {
        alert('comidId 参数为空');
        return false;
      }
      // 每次进来时删除当前缓存下的目录
      this.$nextTick(() => {
        this.init();
      })
      window.addEventListener('scroll', this.scrollfun, true)
    },
    destroyed() {
      window.removeEventListener('scroll', this.scrollfun, true);
    },
    created() {
      // 构建一个缓存
      this.$vlf.createInstance({
        name: 'mh',
        storeName: 'comicInfo',
        verison: '0.0.1',
        size: 5000000
      }).then(info => {
        this.comInfoLg = info;
      });
    }
  };

</script>
